package com.aboo.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.aboo.dao.callback.DeleteCallbackHandler;
import com.aboo.dao.callback.FindCallbackHandler;
import com.aboo.dao.callback.SaveCallbackHandler;
import com.aboo.dao.callback.UpdateCallbackHandler;
import com.aboo.po.BasePO;

public class BaseDao extends HibernateDaoSupport {

	// 持久类类型
	private Class<BasePO> clazz;

	/**
	 * 保存PO
	 * 
	 * @param po
	 * @return
	 */
	public Serializable save(BasePO po) {
		if (po == null) {
			throw new IllegalArgumentException("BasePO cann't be null!");
		}
		return getHibernateTemplate().save(po);
	}

	/**
	 * 批量PO列表
	 * 
	 * @param list
	 * @return
	 */
	public List<Serializable> save(List<BasePO> list) {
		List<Serializable> result = (List<Serializable>) getHibernateTemplate()
				.execute(new SaveCallbackHandler(list, getClazz()));
		return result;
	}

	/**
	 * 删除PO
	 * 
	 * @param po
	 * @return
	 */
	public boolean delete(BasePO po) {
		List<BasePO> list = new ArrayList<BasePO>();
		list.add(po);
		return delete(list);
	}

	/**
	 * 删除PO列表
	 * 
	 * @param po
	 * @return
	 */
	public boolean delete(List<BasePO> list) {
		getHibernateTemplate().execute(
				new DeleteCallbackHandler(list, getClazz()));
		return true;
	}

	/**
	 * 修改PO
	 * 
	 * @param po
	 * @return
	 */
	public boolean update(BasePO po) {
		List<BasePO> list = new ArrayList<BasePO>();
		list.add(po);
		return update(list);
	}

	/**
	 * 修改PO列表
	 * 
	 * @param list
	 * @return
	 */
	public boolean update(List<BasePO> list) {
		getHibernateTemplate().execute(
				new UpdateCallbackHandler(list, getClazz()));
		return true;
	}

	/**
	 * 根据主键来查找PO
	 * 
	 * @param primaryKey
	 * @return
	 */
	public BasePO findByPrimaryKey(int primaryKey) {
		BasePO po = (BasePO) getHibernateTemplate().get(getClazz(), primaryKey);
		return po;
	}

	public List<BasePO> findByCondition(String hqlSQL,
			Map<String, Object> params) {
		List<BasePO> result = (List<BasePO>) getHibernateTemplate().execute(
				new FindCallbackHandler(hqlSQL, params));
		return result;
	}

	public Class<BasePO> getClazz() {
		return clazz;
	}

	public void setClazz(Class<BasePO> clazz) {
		this.clazz = clazz;
	}

}
